package com.ruge.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.ruge.common.util.*;
import com.ruge.system.pojo.entity.SysLogInfo;
import com.ruge.system.pojo.entity.SysUser;
import com.ruge.system.pojo.request.RequestUser;
import com.ruge.system.service.SysLogInfoService;
import com.ruge.system.service.SysLoginService;
import com.ruge.system.pojo.vo.ActiveUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-05  22:31
 * 描述 ： 用户登录  前端控制器
 *
 * @author Administrator
 */
@Slf4j
@RestController
@RequestMapping("login")
@Api(value = "登录controller", tags = {"登录操作接口"})
public class SysLoginController {

    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private SysLogInfoService sysLogInfoService;
    @Resource
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "生成验证码")
    @GetMapping("/captcha")
    public void genCaptcha(HttpServletResponse response, String codeKey) throws IOException {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(116, 36, 4, 1);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator());
        String code = captcha.getCode();
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(codeKey, code);
        opsForValue.getOperations().expire(codeKey, 60, TimeUnit.SECONDS);
        captcha.write(response.getOutputStream());
    }


    @ApiOperation(value = "验证码语音提示")
    @GetMapping("/getCaptchaVoice")
    public RestResponse getCaptchaVoice(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (null == session) {
            return RestResponse.failure("session超时");
        }

        String trueCode = (String) session.getAttribute(Constants.VALIDATE_CODE);
        log.info("从HttpSession中获取验证码[" + trueCode + "]");
        if (null == trueCode) {
            return RestResponse.failure("获取语音提示失败");
        } else {
            //根据验证码生成语音，百度ai技术（文字转语音）
            HashMap<String, Object> options = new HashMap<>(16);
            //语速取值0-9，默认为5语速
            options.put("spd", "1");
            //音调，取值0-9，默认为5中语调
            options.put("pit", "5");
            //发音人选择, 0为女声，1为男声，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女
            options.put("per", "0");
            String vocie = BaiduAiUtil.textToSpeech(trueCode, options);
            return RestResponse.success().setData(vocie);
        }

    }

    @ApiOperation(value = "通过账号和密码登录系统")
    @PostMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
    public RestResponse loginMain(@RequestBody RequestUser requestUser, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(16);
        String error = null;
        //判断用户名或密码是否为空
        if (StringUtils.isBlank(requestUser.getLoginName()) || StringUtils.isBlank(requestUser.getPassword())) {
            return RestResponse.failure("用户名或密码不能为空");
        }

        if (StringUtils.isBlank(requestUser.getRememberMe())) {
            return RestResponse.failure("记住我不能为空");
        }
        if (StringUtils.isBlank(requestUser.getCaptcha())) {
            return RestResponse.failure("验证码不能为空");
        }
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String code = opsForValue.get(requestUser.getCodeKey());
        if (StringUtils.isBlank(code)) {
            return RestResponse.failure("验证码过期");
        } else if (StringUtils.equalsIgnoreCase(String.valueOf(ScriptUtil.eval(code)), requestUser.getCaptcha())) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken loginToken = new UsernamePasswordToken(requestUser.getLoginName(), requestUser.getPassword(), Boolean.parseBoolean(requestUser.getRememberMe()));
            try {
                subject.login(loginToken);
                String token = subject.getSession().getId().toString();
                map.put("token", token);
                //写入登陆日志
                ActiveUser activeUser = ShiroUtil.getActiveUser();
                map.put("activeUser", activeUser);
                SysUser user = activeUser.getUser();
                SysLogInfo loginfo = new SysLogInfo();
                loginfo.setUserId(user.getId());
                loginfo.setUserName(user.getLoginName() + "-" + user.getNickName());
                loginfo.setIp(request.getRemoteAddr());
                sysLogInfoService.save(loginfo);
            } catch (IncorrectCredentialsException e) {
                error = "登录密码错误.";
            } catch (ExcessiveAttemptsException e) {
                error = "登录失败次数过多";
            } catch (LockedAccountException e) {
                error = "帐号已被锁定.";
            } catch (DisabledAccountException e) {
                error = "帐号已被禁用.";
            } catch (ExpiredCredentialsException e) {
                error = "帐号已过期.";
            } catch (UnknownAccountException e) {
                error = "帐号不存在";
            } catch (UnauthorizedException e) {
                error = "您没有得到相应的授权！";
            }
        } else {
            return RestResponse.failure("验证码错误");
        }
        if (StringUtils.isNotBlank(error)) {
            return RestResponse.failure(error).setData(map);
        }
        return RestResponse.success("登录成功").setData(map);
    }


    @ApiOperation(value = "用户退出系统")
    @GetMapping("/logout")
    public RestResponse logout() {
        log.info("用户退出系统:");
        SecurityUtils.getSubject().logout();
        return RestResponse.success("退出成功").setCode(0);
    }

    @ApiOperation(value = "加载用户菜单")
    @GetMapping("/menu")
    public Map<String, Object> menu() {
        log.info("加载用户菜单:" + sysLoginService.menu());
        return sysLoginService.menu();
    }

    @ApiOperation(value = "校验当前用户是否登录")
    @PostMapping("/check")
    public RestResponse check() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            log.info("用户已登录");
            return RestResponse.success("已登录");
        } else {
            log.info("用户未登录");
            return RestResponse.failure("未登录");
        }

    }
}
